package com.bidevalution.controller.api;

import com.bidevalution.business.context.SignLocationContext;
import com.bidevalution.business.dto.SignLocationDto;
import com.bidevalution.business.service.BeSectionParamsService;
import com.bidevalution.business.service.BeSectionSignService;
import com.bidevalution.business.service.BeSignLocationService;
import com.bidevalution.business.service.SmsSendService;
import com.bidevalution.dao.entity.BeSignLocation;
import com.bidevalution.support.context.SmsTemplateCode;
import com.bidevalution.support.util.HttpClientUtil;
import com.bidevalution.support.util.QrCodeUtil;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.qtp.auth.api.UserRightService;
import com.qtp.common.core.TSUser;
import com.qtp.core.common.HttpTookit;
import com.qtp.core.model.Response;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import com.qtp.user.models.Org;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.swing.filechooser.FileSystemView;

import lombok.extern.log4j.Log4j2;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 签到控制层
 * 
 * @author shenh@glodon.com
 * @date 2019-04-29 10:29
 */
@RestController
@RequestMapping("/beSectionSign")
public class BeSectionSignController extends BaseController {

	@Autowired
	private BeSectionSignService beSectionSignService;
	@Value("${signQrCodeUrl}")
	private String signQrCodeUrl;
	@Value("${weChatAppId}")
	private String weChatAppId;
	@Value("${map.key}")
	private String mapKey;
	@Value("${weChatSecret}")
	private String weChatSecret;
	@Value("${wx.accessToken.url}")
	private String accessTokenUrl;
	@Autowired
	private BeSignLocationService beSignLocationService;
	@Autowired
	private EnterPriseInfoDubboService enterPriseInfoDubboService;
	@Autowired
	private BeSectionParamsService beSectionParamsService;

	@Autowired
	private SmsSendService smsSendService;
	

	/**
	 * 签到
	 * 
	 * @param sectionId   标段Id
	 * @param ptSectionId 平台标段Id
	 * @param orgCode     投标单位组织机构代码
	 * @return
	 */
	@RequestMapping(value = "/sectionSign", method = RequestMethod.POST)
	@ResponseBody
	public Response sign(@RequestParam("signAccessCode") String signAccessCode,
			@RequestParam("latitude") String latitude, @RequestParam("longitude") String longitude,
			@RequestParam("speed") String speed, @RequestParam("accuracy") String accuracy,
			@RequestParam("addressZh") String addressZh) {

		try {
			System.out.println(addressZh+":"+signAccessCode+":"+SignLocationContext.get(signAccessCode));
			if(SignLocationContext.get(signAccessCode) != null) {
				System.out.println(SignLocationContext.get(signAccessCode).getOrgId());
				System.out.println(SignLocationContext.get(signAccessCode).getSectionId());
			}
			System.out.println(latitude + longitude + speed + accuracy);
			SignLocationDto signLocationDto = SignLocationContext.get(signAccessCode);
			if(signLocationDto == null) {
				return Response.fail("二维码失效，请重新刷新页面");
			}
			Map<String, Object> params = new HashMap<>();
			params.put("ep_guid", signLocationDto.getOrgId());
			// 获取请求中的参数
			Response<Map<String, Object>> response = enterPriseInfoDubboService.getEnterInfo(params);
			if (response.getResult() != null) {
				BeSignLocation beSignLocation = beSignLocationService.select(signLocationDto.getSectionId(), signLocationDto.getOrgId());
				if (beSignLocation == null) {
					beSignLocation = new BeSignLocation();
					beSignLocation.setId(UUID.randomUUID().toString());
					beSignLocation.setLatitude(latitude);
					beSignLocation.setLongitude(longitude);
					beSignLocation.setOrgId(signLocationDto.getOrgId());
					beSignLocation.setCreateTime(new Date());
					beSignLocation.setSectionId(signLocationDto.getSectionId());
					beSignLocation.setOrgName(String.valueOf(response.getResult().get("ep_name")));
					beSignLocation.setUserId(signLocationDto.getUserId());
					beSignLocation.setAddressZh(addressZh);
					beSignLocationService.insert(beSignLocation);
				} else {
					beSignLocation.setCreateTime(new Date());
					beSignLocation.setUserId(signLocationDto.getUserId());
					beSignLocation.setAddressZh(addressZh);
					beSignLocationService.updateByPrimaryKey(beSignLocation);
				}

			}else {
				return Response.fail("机构不存在:"+signLocationDto.getOrgId());
			}
			String orgCode = String.valueOf(response.getResult().get("ep_org_code"));
			System.out.println(signLocationDto.getSectionId() + orgCode + signLocationDto.getPtSectionId() + signLocationDto.getOrgId());
			beSectionSignService.sign(signLocationDto.getSectionId(), signLocationDto.getPtSectionId(), orgCode, signLocationDto.getOrgId());
			SignLocationContext.remove(signAccessCode);
			//签到成功后发送短信
			smsSendService.sendMsg(SmsTemplateCode.kb0003.getValue(),(String)response.getResult().get("ep_contact_mphone"),null);
			return Response.ok();
		} catch (Exception e) {
			log.error(e.getMessage());
			return Response.fail(e.getMessage());
		}
	}

	/**
	 * 生成签到二维码
	 * 
	 * @param sectionId
	 * @param ptSectionId
	 * @param orgCode
	 * @return
	 */
	@RequestMapping(value = "/generateQrCode", method = RequestMethod.GET)
	@ResponseBody
	public Response<String> generateQrCode(@RequestParam("orgCode") String orgCode,
			@RequestParam("sectionId") String sectionId, @RequestParam("ptSectionId") String ptSectionId) {
		SignLocationDto signLocationDto = new SignLocationDto();
		Map<String, String> paramValueMap = new HashMap<String, String>();
		TSUser tSUser = getTSUser();
		signLocationDto.setUserId(tSUser.getUserGuid());
		signLocationDto.setOrgId(tSUser.getOrgId());
		signLocationDto.setSectionId(sectionId);
		signLocationDto.setPtSectionId(ptSectionId);
		String signAccessCode = UUID.randomUUID().toString().replaceAll("-", "");
		paramValueMap.put("appId", weChatAppId);
		paramValueMap.put("signAccessCode", signAccessCode);
		paramValueMap.put("mapKey", mapKey);
		
		SignLocationContext.put(signAccessCode, signLocationDto);
		String fileId = "";
		try {
			String	url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + weChatAppId + "&redirect_uri="
					+ signQrCodeUrl + "?paramValue=" + Base64.encodeBase64String(GsonUtil.toJson(paramValueMap).getBytes("UTF-8"))
					+ "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
			String path = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "qrcode";
			String fileName = tSUser.getUserGuid().replaceAll("-", "") + "_sign_.jpg";
			File file = new QrCodeUtil().createQrCode(url, path, fileName);
			//获取内网地址
			String innerFileServiceUrl = beSectionParamsService.getOneSysParamValue("INNER_FILE_UPLOAD_URL_PARAM");
			fileId = HttpTookit.sendPostFile(innerFileServiceUrl + "/fileUploadController/uploadWholeFile.do", file, fileName,
					null);
		} catch (Exception e) {
            log.error(e.getMessage(), e);
			return Response.fail("生成二维码异常");
		}
		if(StringUtils.isEmpty(fileId)) {
			return Response.fail("上传失败");
		}
		String fileServiceUrl = "";
		try {
			//获取外网地址
		 	fileServiceUrl = beSectionParamsService.getOneSysParamValue("FILE_UPLOAD_URL_PARAM");
		} catch (Exception e) {
			return Response.fail("获取文件服务器地址失败");
		}
		return Response.ok(fileServiceUrl + "/UploadedFile/" + fileId);
	}

	/**
	 * 获取总的投标单位签到家数
	 * 
	 * @param sectionId 标段Id
	 * @return
	 */
	@RequestMapping(value = "/querySignCount", method = RequestMethod.GET)
	@ResponseBody
	public Response<Long> querySignCount(@RequestParam("sectionId") String sectionId) throws Exception {
		try {
			return Response.ok(beSectionSignService.querySignCount(sectionId));
		} catch (Exception e) {
			return Response.fail("获取已签到的投标单位总数失败");
		}
	}

	@RequestMapping(value = "/getWxConfig", method = RequestMethod.GET)
	public Response<Map<String, String>> getWxConfig(@RequestParam("url") String url) {
		Map<String, String> configMap = new HashMap<String, String>();
		if(accessTokenUrl.contains("?")) {
			accessTokenUrl = accessTokenUrl +"&appid=" + weChatAppId
					+ "&secret=" + weChatSecret; 
		}else {
			accessTokenUrl = accessTokenUrl+"?appid=" + weChatAppId
					+ "&secret=" + weChatSecret;
		}
		System.out.println(accessTokenUrl+"##############################################");
		String accessTokenJson = HttpClientUtil.doGet(accessTokenUrl);
		
		String accessToken = GsonUtil.jsonToMapWithGson(accessTokenJson).get("access_token") == null ? ""
				: GsonUtil.jsonToMapWithGson(accessTokenJson).get("access_token").toString();
		if (StringUtils.isEmpty(accessToken)) {
			return Response.fail("accessToken获取失败:失败原因:" + accessTokenJson);
		}
		configMap.put("accessToken", accessToken);
		String ticket = GsonUtil.jsonToMapWithGson(HttpClientUtil.doGet(
				"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi"))
				.get("ticket").toString();
		// 获取签名signature
		String noncestr = UUID.randomUUID().toString();
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
		// sha1加密
		String signature = SHA1(str);
		configMap.put("noncestr", noncestr);
		configMap.put("timestamp", timestamp);
		configMap.put("signature", signature);
		return Response.ok(configMap);
	}

	/**
	 * 判断投标单位是否已经签到
	 * 
	 * @param sectionId 标段Id
	 * @param orgCode   组织机构代码
	 * @return
	 */
	@RequestMapping(value = "/isSigned", method = RequestMethod.GET)
	@ResponseBody
	public Response<Boolean> isSigned(@RequestParam("sectionId") String sectionId,
			@RequestParam("orgCode") String orgCode) throws Exception {
		try {
			return Response.ok(beSectionSignService.isSigned(sectionId, orgCode));
		} catch (Exception e) {
			return Response.fail("获取投标单位签到信息失败");
		}
	}

	public static void main(String[] args) throws Exception {
		String bString = Base64.encodeBase64String("ddddddddddddddddds".getBytes("UTF-8"));
		System.out.println(new String(Base64.decodeBase64(bString), "UTF-8"));
		
//		// 获取access_token
////		String accessToken = GsonUtil.jsonToMapWithGson(HttpClientUtil.doGet(
////				"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxacecec04c6af72b1&secret=4f236f6fb459a55329816cf77dcd917b"))
////				.get("access_token").toString();
////		String ticket = GsonUtil.jsonToMapWithGson(HttpClientUtil.doGet(
////				"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi")).get("ticket").toString();
////		// 获取ticket07b259700fa61e503ee80670c54c1ea6bf7db32a
////		System.out.println(SHA1(
////				"jsapi_ticket=HoagFKDcsGMVCIY2vOjf9sFid7IP7hNHa-4xFxMC8UCV3iePWOZArarF0yRSZylIGkNFu8xVcXWTrHLIkSTdbQ&noncestr=998c6690-2fff-4b37-a58c-656f261a6120&timestamp=1557272405&url=http://24v775769h.qicp.vip/bid-evalution/bidroom/location"));
////        params.put("access_token",access_token);
////        xml = post("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket",params); 
////        jsonMap  = JSONObject.fromObject(xml);
////        map = new HashMap<String, String>();
////        it = jsonMap.keys();  
////        while(it.hasNext()) {  
////            String key = (String) it.next();  
////            String u = jsonMap.get(key).toString();
////            map.put(key, u);  
////        }
////        String jsapi_ticket = map.get("ticket");
////        System.out.println("jsapi_ticket=" + jsapi_ticket);
//// 
////        //获取签名signature
////        String noncestr = UUID.randomUUID().toString();
////        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
////        String url="http://mp.weixin.qq.com";
////        String str = "jsapi_ticket=" + jsapi_ticket +
////                "&noncestr=" + noncestr +
////                "&timestamp=" + timestamp +
////                "&url=" + url;
////        //sha1加密
////        String signature = SHA1(str);
////        System.out.println("noncestr=" + noncestr);
////        System.out.println("timestamp=" + timestamp);
////        System.out.println("signature=" + signature);
//		// 最终获得调用微信js接口验证需要的三个参数noncestr、timestamp、signature
//		
//		System.out.println(HttpClientUtil.doGet("http://www.tianditu.com/query.shtml?postStr={'lon':116.37304,'lat':39.92594,'ver':1}&type=geocode&tk=a1b0442f5eed2aa6e6c3e624c16cb133"));;
	}

	/**
	 * @author：罗国辉 @date： 2015年12月17日 上午9:24:43 @description： SHA、SHA1加密 @parameter：
	 *             str：待加密字符串 @return： 加密串
	 **/
	public String SHA1(String str) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); // 如果是SHA加密只需要将"SHA-1"改成"SHA"即可
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexStr = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexStr.append(0);
				}
				hexStr.append(shaHex);
			}
			return hexStr.toString();

		} catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
		}
		return null;
	}


}
